package com.yenlien.traceyun.business.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.bean.RestURL;
import com.yenlien.traceyun.business.controller.from.WarehouseForm;
import com.yenlien.traceyun.business.controller.response.BaseSoilView;
import com.yenlien.traceyun.business.dao.BaseSoilDao;
import com.yenlien.traceyun.business.dao.EquipmentDao;
import com.yenlien.traceyun.business.entity.BaseSoil;
import com.yenlien.traceyun.business.entity.CHBasesoil;
import com.yenlien.traceyun.business.interceptor.PassToken;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.BaseSoilService;
import com.yenlien.traceyun.business.service.rest.RestService;
import com.yenlien.traceyun.business.service.rest.usercenter.UserRestService;
import com.yenlien.traceyun.common.utils.QrCodeUtil;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-11-24
 * @description:
 **/

@RestController
@RequestMapping("/basesoil")
public class BaseSoilController extends BaseController {

    @Autowired
    private BaseSoilService baseSoilService;

    @Autowired
    private UserRestService userRestService;

    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    private BaseSoilDao baseSoilDao;

    @Autowired
    private RestService restService;

    @Value("${traceyun.app.id}")
    private String appId;

    /**
     * 保存，修改基地
     *
     * @param soil
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/add")
    public Object save(WarehouseForm soil, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        baseSoilService.save(soil, files, request);
        return success("success");
    }


    // 周年基地
    @PostMapping(value = "/addCHBaseSoil")
    public Object addCHBaseSoil(CHBasesoil chBasesoil, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("files");
        baseSoilService.addCHBaseSoil(chBasesoil, files);
        return success("success");
    }

    @RequestMapping(value = "/findCHBaseSoilByList", method = RequestMethod.POST)
    public Object findCHBaseSoilByList(@RequestBody CHBasesoil chBasesoil) {
        if(StringUtils.isEmpty(chBasesoil.getCompanyId())){
            chBasesoil.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        }
        return success(baseSoilService.findCHBaseSoilByList(chBasesoil));
    }

    @GetMapping(value = "/findCHBaseSoilById")
    public Object findCHBaseSoilById(String id) {
        return success(baseSoilService.findCHBaseSoilById(id));
    }



  /**
     * 地图初始化
     *
     * @return
     */
    @GetMapping(value = "/init")
    public Object findAll() {
        return baseSoilService.findinitAll(UserAuthUtil.getLoginUser().getCompanyId());
    }

    // 根据企业ID获取基地及对应的地块
    @GetMapping(value = "/getByCompId")
    public Object getByCompId(String companyId) {
        return success(baseSoilService.getByCompId(companyId));
    }

    // 获取当前企业下所有地块信息
    @GetMapping(value = "/findByCompId")
    public Object findByCompId(String companyId, String name) {
        return success(baseSoilService.findByCompIdName(companyId, name));
    }








    /**
     * 地图初始化
     *
     * @return
     */
    @GetMapping(value = "/init/{companyId}")
    public Object findAll(@PathVariable("companyId") String companyId) {
        return baseSoilService.findinitAll(companyId);
    }

    /**
     * 监管地图初始化
     *
     * @return
     */
    @GetMapping(value = "/initjg")
    public Object initjg() {
        return baseSoilService.initjg(UserAuthUtil.getLoginUser().getCompanyId());
    }

    @GetMapping(value = "/initjgPlant")
    public Object initjgPlant() {
        return baseSoilService.initjgPlant(UserAuthUtil.getLoginUser().getCompanyId());
    }


    @GetMapping(value = "/breedCount")
    public Object breedCount() {
        Map<String, Integer> map = new HashMap<>();
        String companyId = UserAuthUtil.getLoginUser().getCompanyId();
        JSONObject count = userRestService.findCountByCompanyId(companyId);
        Integer userCount = 0;
        if (count != null) {
            userCount = count.getInteger("data");
        }
        map.put("农户信息", userCount);
        map.put("地块信息", baseSoilDao.breedBaseCount(UserAuthUtil.getLoginUser().getCompanyId()));
        map.put("RFID信息", 20);
        return success(map);
    }


    /**
     * 查询
     *
     * @param baseSoil
     * @return
     */
    @PostMapping(value = "/search")
    public Object search(@RequestBody BaseSoil baseSoil) {
        JSONObject result = new JSONObject();
        if (StringUtils.isEmpty(baseSoil.getCompanyId())) {
            baseSoil.setCompanyId(UserAuthUtil.getLoginUser().getCompanyId());
        }
        Page<BaseSoil> page = baseSoilService.search(baseSoil);
        List<BaseSoilView> views = new ArrayList<>();
        if (page.getContent().size() > 0) {
            for (BaseSoil item : page.getContent()) {
                BaseSoilView view = new BaseSoilView();
                BeanUtils.copyProperties(item, view);
                view.setpName(getParentName(item, page.getContent()));
                views.add(view);
            }
            Set<String> ids = views.stream().map(p -> p.getPid()).collect(Collectors.toSet());
            List<BaseSoil> baseSoils = baseSoilDao.findByIdIn(ids);
            if (baseSoils != null && baseSoils.size() > 0) {
                for (BaseSoilView view : views) {
                    for (BaseSoil baseSoil1 : baseSoils) {
                        if (view.getPid() != null && view.getPid().equals(baseSoil1.getId())) {
                            view.setpName(baseSoil1.getName());
                            break;
                        }
                    }
                }
            }
        }
        for (BaseSoilView baseSoilView : views) {
            JSONObject obj = new JSONObject();
            obj.put("baseSoilId", baseSoilView.getId());
            JSONObject json = restService.postJson(RestURL.PLANTURL + "plant/findByBaseSoilId", obj);
            if (json.get("code").equals("200")) {
                JSONArray data = json.getJSONArray("data");
//                for (int i = 0; i < data.size(); i++) {
                if (data.size() < 1) {
                    continue;
                }
                JSONObject object = new JSONObject((Map<String, Object>) data.get(0));
//                JSONObject object = JSONObject.parseObject(data.get(0).toString());
                String reapStatus = object.getString("reapStatus");
                if (object.get("reapStatus") != null && object.getString("reapStatus").equals("2")) {     //2：全部采收
                    baseSoilView.setStatus("未种植");      //
                } else {
                    baseSoilView.setStatus("种植中");
                }
//                }
            }
        }

        result.put("code", "200");
        result.put("total", page.getTotalElements());
        result.put("rows", views);
        return result;
    }

    /**
     * 获取所有地块信息
     *
     * @return
     */
    @PassToken
    @GetMapping("/findAllPlot")
    public int findAllPlot() {
        List<BaseSoil> all = baseSoilDao.findAll();
        all = all.stream().filter(x -> x.getType() == 2).collect(Collectors.toList());
        return all.size();
    }
    /**
     * 逻辑删除
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/dele/{id}")
    public Object delete(@PathVariable("id") String id) {
        baseSoilDao.ljDelete(id);
        return success("ok");
    }

    /**
     * 加载基地详情
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/load/{id}")
    public Object load(@PathVariable("id") String id) {
        return success(baseSoilDao.findById(id).get());
    }

    /**
     * 加载所有基地
     *
     * @return
     */
    @GetMapping(value = "/loadroot")
    public Object findAllBaseSoild() {
        return success(baseSoilService.findByCompanyId(UserAuthUtil.getLoginUser().getCompanyId()));
    }

    /**
     * 根据pid加载
     *
     * @param pid
     * @param type
     * @return
     */
    @GetMapping(value = "/load/{pid}/{type}")
    public Object findPid(@PathVariable("pid") String pid, @PathVariable("type") int type) {
        return baseSoilService.findByPid(pid, type);
    }

    /**
     * 绑定设备
     *
     * @return
     */
    @PostMapping(value = "/bind/equipment")
    public Object bindEquipment(@RequestBody JSONObject params) {
        CheckParams.checkJson(params, new String[]{"baseSoilId", "equipments"});
        baseSoilService.bindEquipment(params, UserAuthUtil.getLoginUser().getCompanyId());
        return success("ok");
    }

    /**
     * 下载地块码
     *
     * @param id
     * @param request
     * @param response
     */
    @GetMapping(value = "/download/{id}")
    public void downloadCode(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=qr.jpg");
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/scan/baseDetail.html?code=" + id;
        String size = request.getParameter("size");

        QrCodeUtil.encode(url, size, response.getOutputStream());
    }

    private String getParentName(BaseSoil baseSoil, List<BaseSoil> all) {
        if (StringUtils.isEmpty(baseSoil.getPid())) {
            return null;
        }
        if (all != null && all.size() > 0) {
            for (BaseSoil item : all) {
                if (baseSoil.getPid().equals(item.getId())) {
                    return item.getName();
                }
            }
        }
        return null;
    }

    /**
     * 种植首页
     * 地块数量统计
     *
     * @param companyId
     */
    @PostMapping("/areaNumCount")
    public Object areaNumCount(String companyId) {
        if (!StringUtils.isEmpty(companyId)) {
            return success(baseSoilService.areaNumCount(companyId));
        }
        return fail("companyId不能为空");
    }

    //基地信息查询
    @PostMapping("/userAndBaseSoil")
    public Object userAndBaseSoil(@RequestBody JSONObject params) {
        String companyId = params.getString("companyId");
        if (!StringUtils.isEmpty(companyId)) {
            return success(baseSoilService.userAndBaseSoil(companyId));
        }
        return fail("companyId不能为空");
    }

}
